# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.db.models import Q
from books.models import Book,Author
from books.forms import ContactForm
from django.core.mail import send_mail
from forms import PublisherForm


def search(request):
    query = request.GET.get('q','')
    if query:
        qset = (
            Q(title__icontains = query)|
            Q(authors__first_name = query)|
            Q(authors__last_name = query)
        )
        results = Book.objects.filter(qset).distinct()
    else:
        results = []

    return render_to_response('search.html',{
        'query':query,
        'results':results
        })

def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            topic = form.cleaned_data['topic']
            #message = form.cleaned_data['message']
            message = form.clean_message()
            sender = form.cleaned_data['sender']
            print topic,message,sender
            #send_mail( 
            #    'Feedback from your site, topic: %s' % topic, 
            #    message, 
            #    sender, ['chen_jint@qq.com'] 
            #)
            return HttpResponseRedirect('thanks.html')
    else:
        form = ContactForm(initial = {'sender':'user@example.com'})

    return render_to_response('contact.html',{
        'content':'OK',
        'form':form
        }
    )

def add_publisher(request):
    if request.method == 'POST': 
        form = PublisherForm(request.POST) 
        if form.is_valid(): 
            form.save() 
            return HttpResponseRedirect('thanks') 
    else: 
        form = PublisherForm() 
    return render_to_response('add_publisher.html', {'form': form})